package tree;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 117.填充每个节点的下一个右侧节点指针II
 *
 * @author Api
 * @date 2023/10/22 1:00
 */
public class Code117_FillInTheNextRightNodePointerOfEachNodeII {
    static class Node {
        int val;
        Node left;
        Node right;
        Node next;

        public Node() {
        }

        public Node(int val) {
            this.val = val;
        }

        public Node(int val, Node left, Node right, Node next) {
            this.val = val;
            this.left = left;
            this.right = right;
            this.next = next;
        }
    }

    public Node connect(Node root) {
        Deque<Node> queue = new LinkedList<>();
        if (root == null) {
            return root;
        }
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Node nodePre = new Node();
            Node node = new Node();
            for (int i = 0; i < size; i++) {
                if (i == 0) {
                    nodePre = queue.pollFirst(); // 取出一层的头节点
                    node = nodePre;
                } else {
                    node = queue.pollFirst();
                    nodePre.next = node; // 本层前一个节点next指向本节点
                    nodePre = nodePre.next;
                }
                if (node.left != null) {
                    queue.addLast(node.left);
                }
                if (node.right != null) {
                    queue.addLast(node.right);
                }
            }
            node.next = null; // 本层最后一个节点指向NULL
        }
        return root;
    }

    public Node connect1(Node root) {
        Queue<Node> queue = new LinkedList<>();
        if (root == null){
            return root;
        }
        queue.add(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            Node nodePre = null;
            Node node = null;
            for (int i = 0; i < size; i++) {
                if (i == 0){
                    nodePre = queue.poll();
                    node = nodePre;
                }else{
                    node = queue.poll();
                    nodePre.next = node;
                    nodePre = nodePre.next;
                }
                if (node.left != null){
                    queue.add(node.left);
                }
                if (node.right != null){
                    queue.add(node.right);
                }
            }
            node.next = null; // 本层最后一个节点 next 指向 null
        }
        return root;
    }
}
